﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

#define sys_out qDebug()

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("OCR文字识别综合应用  作者：香菇滑稽  blog.csdn.net/wwplh5520370  wechat：784765727");
    QFile f(":qdarkstyle/style.qss");
    if (!f.exists())
    {
        printf("Unable to set stylesheet, file not found\n");
    }
    else
    {
        f.open(QFile::ReadOnly | QFile::Text);
        QTextStream ts(&f);
        qApp->setStyleSheet(ts.readAll());
        f.close();
    }

    swidget = new ScreenWidget;
    connect(swidget,&ScreenWidget::overShot,this,&MainWindow::drawPixmap);
    connect(swidget,&ScreenWidget::cancelShot,[this] {setWindowState(Qt::WindowNoState);});

    timer = new QTimer(this);
    timer->setSingleShot(true);
    connect(timer, &QTimer::timeout, swidget, &ScreenWidget::showFullScreen);

    BaiduOCR = new BaiduOCROnline(this);
    ui->image_path->setReadOnly(true);
    connect(BaiduOCR,&BaiduOCROnline::StdOCRResult,this,&MainWindow::getStdOCRResult);
    connect(BaiduOCR,&BaiduOCROnline::PreciseOCRResult, this,&MainWindow::getPreciseOCRResult);
    connect(BaiduOCR,&BaiduOCROnline::idCardScanResult,this,&MainWindow::getidCardScanResult);
    connect(BaiduOCR,&BaiduOCROnline::bankCardScanResult,this,&MainWindow::getbankCardScanResult);
    connect(BaiduOCR,&BaiduOCROnline::vehicleCardScanResult,this,&MainWindow::getvehicleCardScanResult);
    connect(BaiduOCR,&BaiduOCROnline::driveCardScanResult,this,&MainWindow::getdriveCardScanResult);
    connect(BaiduOCR,&BaiduOCROnline::licensePlateScanResult,this,&MainWindow::getlicensePlateScanResult);
    connect(BaiduOCR,&BaiduOCROnline::vat_invoiceScanResult,this,&MainWindow::getvat_invoiceScanResult);
    connect(BaiduOCR,&BaiduOCROnline::quota_invoiceScanResult,this,&MainWindow::getquota_invoiceScanResult);

    connect(BaiduOCR,&BaiduOCROnline::family_bookScanResult, this, &MainWindow::getfamily_bookScanResult);
    connect(BaiduOCR,&BaiduOCROnline::family_bookScanError, this, &MainWindow::getRecognitionError);
    connect(BaiduOCR,&BaiduOCROnline::family_bookGoOn, this, &MainWindow::familyRecognition);

    ParaDialog = new Parameters;
    connect(ParaDialog, &Parameters::userParameters, this, &MainWindow::setIniFile);
//    connect(ParaDialog, &Parameters::cancleSet, [this]{setWindowState(Qt::WindowNoState);});

    QString file_path = QApplication::applicationDirPath() + "/userParameters/config.ini";
    iniFile = new QSettings(file_path, QSettings::IniFormat, this);
    if(!QFile::exists(file_path))
    {
        QMessageBox::information(this, "提示", "未找到文件" + file_path + ".\n请设置应用参数.");
    }
    else
    {
        iniFile->beginGroup("API-parameters");
        BaiduOCR->getAccToken(iniFile->value("API_key").toString(), iniFile->value("Secret_key").toString());
        iniFile->endGroup();
    }
    clipboard = QApplication::clipboard();
}

MainWindow::~MainWindow()
{
    ParaDialog->deleteLater();
    delete ui;
}

void MainWindow::setIniFile(const QString& api_key, const QString& secret_key)
{
    this->setWindowState(Qt::WindowNoState);

    iniFile->clear();
    iniFile->beginGroup("API-parameters");
    iniFile->setValue("API_key", api_key);
    iniFile->setValue("Secret_key", secret_key);
    iniFile->endGroup();

    BaiduOCR->getAccToken(api_key, secret_key);
}

void MainWindow::getStdOCRResult(QString content)
{
    ui->tBocr->setText(content);
}
void MainWindow::getPreciseOCRResult(QString content)
{
    ui->tBhocr->setText(content);
}
void MainWindow::getidCardScanResult(QString content)
{
    ui->tBidcard->setText(content);
}
void MainWindow::getbankCardScanResult(QString content)
{
    ui->tBbankcard->setText(content);
}
void MainWindow::getvehicleCardScanResult(QString content)
{
    ui->tBvehiclecard->setText(content);
}
void MainWindow::getdriveCardScanResult(QString content)
{
    ui->tBdrivecard->setText(content);
}
void MainWindow::getlicensePlateScanResult(QString content)
{
    ui->tBlicensePlate->setText(content);
}
void MainWindow::getvat_invoiceScanResult(QString content)
{
    ui->tBvat_invoice->setText(content);
}
void MainWindow::getquota_invoiceScanResult(QString content)
{
    ui->tBquota_invoice->setText(content);
}
void MainWindow::getfamily_bookScanResult(QMap<QString, QString> content)
{
    allResults<<content;
    ui->familyLog->append("姓名：" + content.value("Name"));
    ui->familyLog->append("性别：" + content.value("Sex"));
    ui->familyLog->append("民族：" + content.value("Nation"));
    ui->familyLog->append("身份证号：" + content.value("CardNo"));
    ui->familyLog->append("与户主关系：" + content.value("Relationship"));
    ui->familyLog->append("====================================================");
}
void MainWindow::on_open_img_triggered()
{
    QString filename = QFileDialog::getOpenFileName();
    if(!filename.isEmpty())
    {
        ui->image_path->setText(filename);
        QImage Image(filename);
        ui->image_view->setPixmap(QPixmap::fromImage(Image.scaled(ui->image_view->width(),ui->image_view->height(),Qt::KeepAspectRatio)));
    }
}

void MainWindow::on_act_baidu_triggered()
{
    QString Image = ui->image_path->text();
    switch (ui->tabWidget->currentIndex())
    {
        case 0:
        {
            BaiduOCR->StdOCR(Image);
            break;
        }
        case 1:
        {
            BaiduOCR->PreciseOCR(Image);
            break;
        }
        case 2:
        {
            BaiduOCR->idCardScan(Image, id_card_fside);
            break;
        }
        case 3:
        {
            BaiduOCR->bankCardScan(Image);
            break;
        }
        case 4:
        {
            BaiduOCR->vehicleCardScan(Image);
            break;
        }
        case 5:
        {
            BaiduOCR->driveCardScan(Image);
            break;
        }
        case 6:
        {
            BaiduOCR->licensePlateScan(Image);
            break;
        }
        case 7:
        {
            BaiduOCR->vat_invoiceScan(Image);
            break;
        }
        case 8:
        {
            BaiduOCR->quota_invoiceScan(Image);
            break;
        }
    }
}

void MainWindow::drawPixmap(const QPixmap& pixmap)
{
    setWindowState(Qt::WindowNoState);
    ui->image_path->setText(QString("%1/screen_shot.png").arg(qApp->applicationDirPath()));
    ui->image_view->setPixmap(pixmap.scaled(ui->image_view->width(),ui->image_view->height(),Qt::KeepAspectRatio));
}
void MainWindow::on_shot_screen_triggered()
{
    setWindowState(Qt::WindowMinimized);
    timer->start(500);  //定时器触发截图，等待界面最小化完成
}

void MainWindow::on_actHelp_triggered()
{
    QMessageBox::information(this,"快捷键说明","打开图片：Ctrl + O\n面向百度：Ctrl + U\n截图：Alt + S");
}

void MainWindow::on_actSetPara_triggered()
{
    ParaDialog->show();

}

void MainWindow::on_actAbout_triggered()
{
    QMessageBox::information(this, "关于", "作者：香菇滑稽之谈\n主页：blog.csdn.net/wwplh5520370\nwechat：784765727");
}

void MainWindow::on_openDir_clicked()
{
    QString objPath = QFileDialog::getExistingDirectory();
    ui->image_path->setText(objPath);
    QDir objDir(objPath);
    QFileInfoList allFiles = objDir.entryInfoList(QDir::Files);
    if(allFiles.isEmpty())
        return;
    familyList.clear();
    for(QFileInfo info:allFiles)
    {
        sys_out<<info.filePath();
        familyList<<info.filePath();    //支持jpg/jpeg/png/bmp
        familyList1<<info.filePath();
    }
}

void MainWindow::familyRecognition()
{
    if(familyList.isEmpty())
        return;
//    QImage Image(familyList.first());
//    BaiduOCR->family_bookScan(Image);
    BaiduOCR->family_bookScan(familyList.first());
    familyList.removeFirst();
}
void MainWindow::on_postRequest_clicked()
{
    allResults.clear();
    familyRecognition();
}
void MainWindow::getRecognitionError(QString err)   //户口本识别错误
{
    ui->familyLog->append(err);
}

void MainWindow::on_writeToExcel_clicked()
{
    sys_out<<allResults;
    QString fileNmae = QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + ".xlsx";
    // step1：连接控件
    QAxObject* excel = new QAxObject(this);
    excel->setControl("Excel.Application");  // 连接Excel控件
    excel->dynamicCall("SetVisible (bool Visible)", "false"); // 不显示窗体
    excel->setProperty("DisplayAlerts", false);  // 不显示任何警告信息。如果为true, 那么关闭时会出现类似"文件已修改，是否保存"的提示

    // step2: 打开工作簿
    QAxObject* workbooks = excel->querySubObject("WorkBooks"); // 获取工作簿集合
    // 打开工作簿方式一：新建
//    workbooks->dynamicCall("Add"); // 新建一个工作簿
//    QAxObject* workbook = excel->querySubObject("ActiveWorkBook"); // 获取当前工作簿
    // 打开工作簿方式二：打开现成
    QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", QApplication::applicationDirPath() + "/record.xlsx"); // 从控件lineEdit获取文件名

    // step3: 打开sheet
    QAxObject* worksheet = workbook->querySubObject("WorkSheets(int)", 1); // 获取工作表集合的工作表1， 即sheet1


    // step4: 获取行数，列数
    QAxObject* usedrange = worksheet->querySubObject("UsedRange"); // sheet范围
    int intRowStart = usedrange->property("Row").toInt(); // 起始行数
    int intColStart = usedrange->property("Column").toInt();  // 起始列数


    QAxObject *rows = usedrange->querySubObject("Rows");  // 行
    QAxObject *columns = usedrange->querySubObject("Columns");  // 列

    int intRow = rows->property("Count").toInt(); // 行数
    int intCol = columns->property("Count").toInt();  // 列数

    // step5: 读和写
    // 读方式一（坐标）：
    QAxObject* cell = nullptr;
    cell = worksheet->querySubObject("Cells(int, int)", 1, 1);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "姓名"); // 设置单元格的值
    cell = worksheet->querySubObject("Cells(int, int)", 1, 2);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "性别"); // 设置单元格的值
    cell = worksheet->querySubObject("Cells(int, int)", 1, 3);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "民族"); // 设置单元格的值
    cell = worksheet->querySubObject("Cells(int, int)", 1, 4);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "身份证号"); // 设置单元格的值
    cell = worksheet->querySubObject("Cells(int, int)", 1, 5);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "与户主关系"); // 设置单元格的值
    cell = worksheet->querySubObject("Cells(int, int)", 1, 6);  //获单元格
    cell->dynamicCall("SetValue(conts QVariant&)", "图片位置"); // 设置单元格的值

    int curRow = intRow + 1;
    for(int index = 0; index < allResults.size(); index++)
    {
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 1);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", allResults.at(index).value("Name")); // 设置单元格的值
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 2);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", allResults.at(index).value("Sex")); // 设置单元格的值
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 3);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", allResults.at(index).value("Nation")); // 设置单元格的值
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 4);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", allResults.at(index).value("CardNo")); // 设置单元格的值
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 5);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", allResults.at(index).value("Relationship")); // 设置单元格的值
        cell = worksheet->querySubObject("Cells(int, int)", curRow, 6);  //获单元格
        cell->dynamicCall("SetValue(conts QVariant&)", familyList1.at(index)); // 设置单元格的值
        curRow++;
    }

    // step6: 保存文件
    workbook->dynamicCall("Save()");  //保存文件
    workbook->dynamicCall("Close(Boolean)", false);  //关闭文件
    // 注意一定要用QDir::toNativeSeparators, 将路径中的"/"转换为"\", 不然一定保存不了
    workbook->dynamicCall("Close (Boolean)", false);  //关闭文件

    excel->deleteLater();
    workbooks->deleteLater();
    workbook->deleteLater();
    worksheet->deleteLater();
    usedrange->deleteLater();
    rows->deleteLater();
    columns->deleteLater();
    cell->deleteLater();
    ui->familyLog->append("数据写入表格完成。\n===================================");
}


void MainWindow::on_actCopy_triggered()
{
//    QClipboard *clipboard = QApplication::clipboard();   //获取系统剪贴板指针

//    clipboard->text();                                   //获取剪贴板内容
    QString str_text;
    int index = ui->tabWidget->currentIndex();
    switch (index)
    {
    case 0:
    {
        str_text = ui->tBocr->toPlainText();
        break;
    }
    case 1:
    {
        str_text = ui->tBhocr->toPlainText();
        break;
    }
    case 2:
    {
        str_text = ui->tBidcard->toPlainText();
        break;
    }
    case 3:
    {
        str_text = ui->tBbankcard->toPlainText();
        break;
    }
    case 4:
    {
        str_text = ui->tBvehiclecard->toPlainText();
        break;
    }
    case 5:
    {
        str_text = ui->tBdrivecard->toPlainText();
        break;
    }
    case 6:
    {
        str_text = ui->tBlicensePlate->toPlainText();
        break;
    }
    case 7:
    {
        str_text = ui->tBvat_invoice->toPlainText();
        break;
    }
    case 8:
    {
        str_text = ui->tBquota_invoice->toPlainText();
        break;
    }
    case 9:
    {
        str_text = ui->familyLog->toPlainText();
        break;
    }
    }
    clipboard->setText(str_text);                        //设置剪贴板内容
}

